<template>
    <div style="text-align:right;">
        <el-dropdown @command="handleBatchCommand" style="margin-right:10px">
            <el-button size="small" type="primary">
                批量操作<el-icon class="el-icon--right">
                    <arrow-down />
                </el-icon>
            </el-button>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item command="review">批量申请审核</el-dropdown-item>
                    <el-dropdown-item command="online">批量上线</el-dropdown-item>
                    <el-dropdown-item command="offline">批量下线</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <el-button type="primary" size="small" @click="handleCreate">
            <el-icon>
                <plus />
            </el-icon>
            新建
        </el-button>
    </div>
    <el-table class="mt10 mb10" v-loading="isloading" :data="tableData.listData" border :height="tableHeight"
        highlight-current-row @selection-change="handleSelectionChange" @row-click="(row) => {handleRowClick(row)}"
        ref="tableref">
        <el-table-column type="selection" width="40" />
        <el-table-column label="缩略图" width="60">
            <template #default="{row}">
                <el-image v-if="row.thumbs.length > 0 && typeof row.thumbs[0] == 'object'" :preview-src-list="srcList"
                    :initial-index="srcList.indexOf(row.thumbs[0].viewurl)"
                    :src="(row.thumbs[0].isself == 1 && row.thumbs[0].sourcefrom == 'cloudstorage') ? row.thumbs[0].viewurl+'&width=50' : row.thumbs[0].viewurl" />
            </template>
        </el-table-column>
        <el-table-column label="子集ID" width="120px" prop="seriesid" />
        <el-table-column label="集号" width="120px">
            <template #default="{row}">
                <span v-if="row.episodenum">{{row.episodenum}}</span>
                <span v-else>-</span>
            </template>
        </el-table-column>
        <!--<el-table-column label="集号" prop="episodenum" width="120px" />-->
        <el-table-column label="子集名称" :show-overflow-tooltip="true">
            <template #default="{row}">
                <a href="javascript:;" @click.stop="handleSeriesDetail(row)" v-if="mediatype == 'liveroom'">
                    {{row.name}}
                </a>
                <span v-else>{{row.name}}</span>
            </template>
        </el-table-column>
        <el-table-column label="时长" width="120px">
            <template #default="{row}">
                <span v-if="row.duration">{{row.duration}}</span>
                <span v-else>0</span>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150px" align="center" prop="cts">
            <el-table-column label="更新时间" width="150px" align="center" prop="mts">
                <template #default="{row}">
                    {{row.ctime != null ? row.ctime.replace('T', ' ').replace('Z', '') : '-'}}<br />
                    {{row.mtime != null ? row.mtime.replace('T', ' ').replace('Z', '') : '-'}}
                </template>
            </el-table-column>
        </el-table-column>
        <el-table-column label="审核状态" width="70px">
            <template #default="{row}">
                <span v-if="row.state == 0">未提交</span>
                <span v-else-if="row.state == 1">审核中</span>
                <span v-else-if="row.state == 2">审核通过</span>
                <span v-else-if="row.state == 3">审核失败</span>
                <span v-else-if="row.state == 4">免审</span>
                <span v-else>-</span>
            </template>
        </el-table-column>
        <el-table-column label="付费类型" width="70px" align="center">
            <template #default="{row}">
                <span v-if="row.paytype == 0" style="color:#67C23A">免费</span>
                <span v-else-if="row.paytype == 1" style="color:#f56c6c">付费</span>
                <span v-else>-</span>
            </template>
        </el-table-column>
        <el-table-column label="状态" width="80px">
            <template #default="{row}">
                <template v-if="row.state == 2 || row.state == 4">
                    <el-button v-if="row.inuse == 1" type="text" size="mini" @click.stop="handleOnOff(row)">上线
                    </el-button>
                    <el-button v-else type="text" style="color:#f56c6c" size="mini" @click.stop="handleOnOff(row)">下线
                    </el-button>
                </template>
                <template v-else>
                    <el-button v-if="row.inuse == 1" type="text" size="mini" :disabled="true">上线</el-button>
                    <el-button v-else type="text" size="mini" :disabled="true">下线</el-button>
                </template>
            </template>
        </el-table-column>
        <el-table-column label="排序" width="80px" v-if="mediatype=='liveroom'">
            <template #default="scope">
                <!--<el-button @click.stop="handleSort(scope.row,'down')" type="text" :disabled="scope.row.topno > 1 ? true : false"><el-icon><SortDown /></el-icon></el-button>
                <el-button @click.stop="handleSort(scope.row,'up')" type="text" :disabled="scope.row.topno > 1 ? true : false"><el-icon><SortUp /></el-icon></el-button>-->
                <SeriesResort :row="scope.row" :updisabled="scope.row.topno > 1 ? true : false"
                    :downdisabled="scope.row.topno > 1 ? true : false" @reloadSeries="reloadSeries"></SeriesResort>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160px">
            <template #default="scope">
                <el-button v-if="scope.row.state == 0 || scope.row.state == 3" type="text" size="mini"
                    @click.stop="handleReview(scope.row)">申请审核</el-button>
                <el-button v-else type="text" size="mini" :disabled="true">申请审核</el-button>
                <el-button v-if="scope.row.state != 1" type="text" size="mini" @click.stop="handleEdit(scope.row)">
                    编辑
                </el-button>
                <el-button v-else type="text" size="mini" :disabled="true">
                    编辑
                </el-button>
                <!--<el-button type="text" size="mini" @click.stop="handleDelete(scope.row)">
                    删除
                </el-button>-->
                <series-delete-button :row="scope.row" @reloadSeries="reloadSeries"></series-delete-button>
                <!--<el-button v-if="scope.row.topno == 1" type="text" size="mini" @click.stop="handleSeriesToTop(scope.row, 1)">置顶</el-button>
                <el-button v-else type="text" size="mini" @click.stop="handleSeriesToTop(scope.row, 0)">取消置顶</el-button>-->
                <br>
                <SeriesToTop :row="scope.row" @reloadSeries="reloadSeries"></SeriesToTop>
            </template>
        </el-table-column>
    </el-table>
    <el-row>
        <el-col :span="24">
            <table-pagination :queryList="queryList" :total="tableData.total" @pagination="getDataList" />
        </el-col>
    </el-row>
    <create-dialog :visible="dialogCreateVisible" :toDialogData="toDialogData" @cancelDialog="cancelDialog"
        @getData="getDataList" :key="dialogKey" ref="createDialogRef" />
</template>

<script>
    import { useRoute,useRouter } from 'vue-router';
    import {ref,reactive,nextTick,onMounted} from 'vue';
    import TablePagination from "@/views/public/TablePagination";
    import { getSeries, seriesOnOff } from "@/api/series/series";
    import {useStore} from 'vuex'
    import {Plus, ArrowDown} from "@element-plus/icons"
    import CreateDialog from './CreateDialog'
    import {ElMessage, ElMessageBox} from 'element-plus'
    import {seriesReview} from '@/api/media/review'
    import SeriesResort from '@/components/Common/SeriesResort'
    import SeriesToTop from '@/components/Common/SeriesToTop'
    import SeriesDeleteButton from '@/components/Common/SeriesDeleteButton'
    export default {
        name: "serieslist",
        components: {
            TablePagination,
            Plus,
            ArrowDown,
            CreateDialog,
            SeriesResort,
            SeriesToTop,
            SeriesDeleteButton
        },
        setup() {
            const store = useStore()
            const route = useRoute()
            const router = useRouter()
            const corpid = store.getters.corpinfo.corpid
            const subid = store.getters.subinfo.subid
            const uid = store.getters.userinfo.uid
            // 图片预览
            const srcList = ref([])
            // 接收参数
            const mediaid = route.query.mediaid
            const groupid = route.query.groupid
            const mediatype = route.query.mediatype
            // 搜索条件
            const queryList = reactive({
                'page': 1,
                'pagesize': 10,
                'mediaid': mediaid,
                'corpid': store.getters.corpinfo.corpid,
                'keyword': ''
            })
            // 列表相关
            const isloading = ref(true)
            const tableData = reactive({
                total: 0,
                listData: []
            })
            const getDataList = () => {
                isloading.value = true;
                getSeries(queryList).then(response => {
                    isloading.value = false;
                    const {total, list, hasprevpage, hasnextpage} = response.data
                    tableData.total = total
                    tableData.listData = list
                    tableData.hasprevpage = hasprevpage
                    tableData.hasnextpage = hasnextpage
                    list.forEach(item => {
                        if( typeof item.thumbs[0] == 'object' ){
                            srcList.value.push(item.thumbs[0].viewurl)
                        }
                    })
                })
            }
            getDataList()

            // 媒资添加和编辑
            const createDialogRef = ref('')
            const dialogKey = ref('')
            const dialogCreateVisible = ref(false)
            const handleCreate = () => {
                dialogKey.value = new Date().getTime()
                toDialogData.value.seriesid = undefined
                dialogCreateVisible.value = true
                nextTick(() => {
                    createDialogRef.value.init()
                })
            }
            const handleEdit = (seriesData) => {
                if( mediatype == 'liveroom' ) {

                    if( router.currentRoute.value.name == 'mediaslistserieslistall' ){
                        router.push({name:'mediaallseriesdetail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesData.seriesid,isedit:1}})
                    }else if( router.currentRoute.value.name == 'mediaslistserieslistliveroom' ){
                        router.push({name:'medialiveroomseriesdetail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesData.seriesid,isedit:1}})
                    }else{
                        router.push({path:'/media/series/detail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesData.seriesid,isedit:1}})
                    }
                }else{
                    dialogKey.value = new Date().getTime()
                    dialogCreateVisible.value = true
                    toDialogData.value.seriesid = seriesData.seriesid
                    nextTick(() => {
                        createDialogRef.value.init()
                    })
                }
            }
            const cancelDialog = () => {
                dialogCreateVisible.value = false
            }
            const toDialogData = ref({
                mediaid: mediaid,
                mediatype: mediatype,
                groupid: groupid,
                corpid: corpid,
                subid: subid,
                uid: uid
            })

            // 子集审核
            const handleReview = (row) => {
                ElMessageBox.confirm(
                    '确定申请 ' + row.name + ' 进行审核吗？',
                    '媒资子集审核',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    seriesReview({seriesids:[row.seriesid]}).then(response => {
                        if( response.errcode == 0 ){
                            ElMessage({type: 'success', message: response.msg, duration: 2000})
                            getDataList()
                        }else{
                            console.log(response)
                        }
                    })
                }).catch((err) => {
                    console.log(err)
                })
            }

            // 子集删除
            const handleDelete = (row) => {
                ElMessageBox.confirm(
                    '确定删除 ' + row.name + ' 吗？',
                    '媒资子集删除',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    ElMessage({ type: 'success', message: '删除成功', duration: 2000 })
                    /*seriesReview({ seriesids: [row.seriesid] }).then(response => {
                        if (response.errcode == 0) {
                            ElMessage({ type: 'success', message: response.msg, duration: 2000 })
                            getDataList()
                        } else {
                            console.log(response)
                        }
                    })*/
                }).catch((err) => {
                    console.log(err)
                })
            }

            //上下线
            const handleOnOff = (row) => {
                let option = ''
                let inputPlace = ''
                if( row.inuse == 1 ){
                    option = '下线'
                    inputPlace = '请填写下线原因（必填）'
                }else{
                    option = '上线'
                    inputPlace = '请填写上线原因（选填）'
                }
                ElMessageBox.prompt('确定 <strong>' + row.name + '</strong> 进行 <strong>' + option + '</strong> 吗？', '子集状态变更', {
                    dangerouslyUseHTMLString:true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: (val) => {
                        if (row.inuse == 1 && val === null) {
                            return false;//初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
                        }else{
                            return true;
                        }
                    },
                    inputPlaceholder: inputPlace,
                    inputErrorMessage: '请输入下线原因',
                }).then((val) => {
                    let postInuse = row.inuse==1? 0: 1
                    // console.log(val,postInuse)
                    seriesOnOff({inuse:postInuse, seriesids:[row.seriesid], comments:val.value}).then(response => {
                        if( response.errcode == 0 ){
                            ElMessage({type: 'success', message: response.msg, duration: 2000})
                            getDataList()
                        }else{
                            console.log(response)
                        }
                    })
                }).catch((err) => {
                    console.log(err)
                })
            }
            //复选框
            const batchCheckBoxData = ref([])
            const tableref = ref(null)
            const handleSelectionChange = (val) => {
                if(val.length > 0){
                    batchCheckBoxData.value = []
                    val.forEach(function(item){
                        batchCheckBoxData.value.push(item.seriesid)
                    })
                    console.log(batchCheckBoxData.value)
                }
            }
            const handleRowClick = (row) => {
                tableref.value.toggleRowSelection(row)
            }
            //table自适应
            const tableHeight=ref()
            onMounted( () => {
                tableHeight.value =
                window.innerHeight - tableref.value.$el.offsetTop - 80;
            })
            // 批量操作
            const handleBatchCommand =(command) => {
                if( batchCheckBoxData.value.length == 0 ){
                    ElMessage({type: 'warning', message: '请选择批量操作的数据', duration: 2000})
                    return
                }
                let elMsg = ''
                let inputPlac = ''
                switch(command){
                    case 'review':
                        elMsg = '批量申请审核'
                        break
                    case 'online':
                        elMsg = '批量上线'
                        inputPlac = '请输入批量上线的原因（选填）'
                        break
                    case 'offline':
                        elMsg = '批量下线'
                        inputPlac = '请输入批量下线的原因（必填）'
                        break
                }
                // 需要填写提交内容的提示框
                if( command == 'online' || command == 'offline' ){
                    ElMessageBox.prompt('确定 ' + elMsg + ' 吗？', '批量操作', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputValidator: (val) => {
                            if (command == 'offline' && val === null) {
                                return false;//初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
                            }else{
                                return true;
                            }
                        },
                        inputPlaceholder:inputPlac,
                        inputErrorMessage: '请输入下线原因',
                    }).then((val) => {
                        let postInuse = command == 'online'? 1: 0
                        seriesOnOff({inuse:postInuse, seriesids:batchCheckBoxData.value, comments:val.value}).then(response => {
                            if( response.errcode == 0 ){
                                ElMessage({type: 'success', message: response.msg, duration: 2000})
                                getDataList()
                            }else{
                                console.log(response)
                            }
                        })
                    }).catch((err) => {
                        console.log(err)
                    })
                // 仅是确定的提示框
                }else{
                    ElMessageBox.confirm(
                        '确定 ' + elMsg + ' 吗？',
                        '批量操作',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(() => {
                        if(command == 'review'){
                            seriesReview({seriesids:batchCheckBoxData.value}).then(response => {
                                if( response.errcode == 0 ){
                                    ElMessage({type: 'success', message: response.msg, duration: 2000})
                                    getDataList()
                                }else{
                                    console.log(response)
                                }
                            })
                        }
                    }).catch((err) => {
                        console.log(err)
                    })
                }
            }

            // 直播间子集跳转详情
            const handleSeriesDetail = (seriesInfo) => {
                if( router.currentRoute.value.name == 'mediaslistserieslistall' ){
                    router.push({name:'mediaallseriesdetail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesInfo.seriesid}})
                }else if( router.currentRoute.value.name == 'mediaslistserieslistliveroom' ){
                    router.push({name:'medialiveroomseriesdetail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesInfo.seriesid}})
                }else{
                    router.push({path:'/media/series/detail',query: {mediaid : mediaid,groupid:groupid,mediatype:mediatype,seriesid:seriesInfo.seriesid}})
                }
            }

            const reloadSeries = () => {
                getDataList()
            }
            return {
                isloading,
                mediatype,
                srcList,
                tableData,
                queryList,
                getDataList,
                createDialogRef,
                dialogKey,
                dialogCreateVisible,
                toDialogData,
                handleCreate,
                handleEdit,
                cancelDialog,
                handleReview,
                handleDelete,
                handleOnOff,
                tableref,
                tableHeight,
                handleSelectionChange,
                handleRowClick,
                handleBatchCommand,
                handleSeriesDetail,
                reloadSeries
            }
        }
    }
</script>

<style scoped  lang="scss">

</style>
